var app = getApp();
var util = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
import getUserCard from "../../utils/getUserCard.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    swiperCurrent: 0,
    CurrentPid: 0,
    cateId: 0,
    productName: "",
    productPrice: 0,
    buynumber: 0,
    stockNumber: '',
    ExpireTime: '',
    vid: "",
    procardid: 0,//商家的玖玖客id(用于生成海报,朋友圈分享)
    seltoid: 0, //商家uid
    saleUid: 0,//推荐人uid
    name: "",
    startDate: "",
    description: "",
    productImageList: [],
    pimages: "",
    DetailPics: [],
    ShadowPrice: "",
    marketPrice:0,  //市场价
    showVideo: true,
    isAccredit: false,
    cartNumber: 0,
    sumPrice: 0,
    salecount: 0,
    cartResult: [],
    mobile: '',
    company: '',
    createUid: 0,
    skulist: [],
    showDialog: false,
    selectSkuname: '',
    top: 60,
    state: 0,//0在售1下架
    lastLiveList: [],
    // isCommision: 0,//1带佣金2不带佣金
    jump: 0,//0普通购买，1带佣金代金券套餐购买,4购买玖玖卡【全国通用】,11 云加盟
    tobuyBtn: '立即抢购',
    isBackEditor: false,
    cardType: 0,//4玖玖通用卡5福鲤卡
    isUseNow: '',//是否购买后立即生效
    limit: '',//是否限购
    isSend: '',//是否支持转赠
    serverTime: '',
    outsaletime: '',
    buyerList: [],
    clientCount: 0,
    clientList: [],
    proStaffid: 0,//商品所属商家的staffid
    optionPrice: 0,
    lastPrice: 0, //追加的规格价格
    regions: []  //招商区域(云加盟)
  },

  // 获取购买该商品的人
  getBuyers: function (pid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/order/GetOrderListByPid?pid=' + pid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data && res.data.Data.length > 0) {
            let buyerList = res.data.Data;
            for (let i = 0; i < buyerList.length; i++) {
              if (buyerList[i].NickName.trim().length > 7) {
                buyerList[i].NickName = buyerList[i].NickName.trim().substr(0, 7) + '**';
              }
              buyerList[i].NickName += '购买了该商品';
            }
            that.setData({
              buyerList: buyerList
            })
          }
        }
      },
    })
  },

  getProductActoin: function (pid, createuid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/product/GetProductActoin?pid=' + pid + '&createuid=' + createuid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.ShowCount > 0) {
            let list = res.data.Data.ClientList;
            that.setData({
              clientCount: res.data.Data.ShowCount,
              clientList: list
            })
          }
        }
      },
    })
  },
  // 看直播
  toLookLive: function (e) {
    let roomid = e.currentTarget.dataset.roomid;
    let cardId = wx.getStorageSync('cardId');
    wx.navigateTo({
      url: 'plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=' + roomid + '&custom_params=' + encodeURIComponent(JSON.stringify({
        cardId: cardId,
        saleUid: 0
      })),
    })
  },

  // 优惠券抢购
  toBuyCoupon: function (e) {
    let that = this;
    var pid = that.data.CurrentPid;
    let stock = that.data.stockNumber;
    let state = that.data.state;

    if (that.data.tobuyBtn == '已售罄') {
      wx.showToast({title: '商品已售罄',icon:'none'}); return;
    }
    if (state == 1) {
      wx.showToast({title: '商品已下架',icon:'none'});return;
    }
    if (stock < 1) {
      wx.showToast({title: '商品库存不足',icon:'none'});return;
    }
    let back = that.data.jump == 1 ? '/pages/productDetails/index' : '/pages/classes-new/index';
    if(!that.isLogin(back)){
      return;
    }

    let isCoupon = that.data.cateId==377 || that.data.cateId==378 ? 3 : 1;   
    that.toCard(isCoupon);
  },

   // 索取资料
   toEmail: function (e) {
    let that = this;
    let back = '/pages/classes-new/index';
    if (that.data.jump == 1) {
      back = '/pages/productDetails/index';
    }
    if(!that.isLogin(back)){
      return;
    }
    that.toCard(2);
  },

  toCard: function(isCoupon){
    let that = this;
    var pid = that.data.CurrentPid;
    let stock = that.data.stockNumber;
        
    that.clearCart(function (flag) {
      if (flag) { //清空购物车完成
        wx.request({
          url: app.globalData.host + '/api/cart/AddProduct',
          data: {
            uid: app.globalData.userInfo.Uid,
            pid: pid,
            buyCount: 1,
            optionIds: '',
            createUid: that.data.seltoid
          },
          success: function (res) {
            if (res.data.Code == 0) {
              // 跳转优惠券购物车页面
              let jump = that.data.jump;
              if (that.data.cardType == 4) {//玖玖通用卡
                jump = 4
              }
              wx.navigateTo({
                url: '/order/order/cart/index?isCoupon='+ isCoupon +'&stockNumber=' + stock + '&saleUid=' + that.data.saleUid + '&jump=' + jump + '&seltoid=' + that.data.seltoid,
              })
            } else {
              util.showModal(res.data.Message);              
            }
          }
        })
      }
    })
  },
  toCall: function(){

  },
  // 清空购物车
  clearCart: function (cb) {
    let that = this;
    if (app.globalData.userInfo) {
      wx.request({
        url: app.globalData.host + '/api/Cart/Clear?uid=' + app.globalData.userInfo.Uid + '&createUid=' + that.data.seltoid,
        success: function (res) {
          cb(res.data.Data);
        }
      })
    } else {
      that.clearCart(cb);
    }

  },
  // 弹出选规格弹窗
  chooseSku: function (e) {
    let that = this;
    if (that.data.state == 1) {
      util.showModal('商品已下架'); return;
    }
    if (that.data.stockNumber <= 0) {
      util.showModal('商品库存不足'); return;
    }
    let lastPrice = that.data.productPrice + that.data.optionPrice;
    that.setData({
      showDialog: !that.data.showDialog,
      lastPrice: parseFloat(lastPrice).toFixed(2)
    })
  },

  onLoad: function (e) {
    let that = this;
    util.isAccredit(function (isAccredit) {
      that.setData({isAccredit: isAccredit})
    });
    if (e.pid) {   
      that.setData({CurrentPid: e.pid});      
    }
    if (e.cardType) {
      that.data.cardType = e.cardType
    }
    if (e.proStaffid) {
      that.setData({proStaffid: e.proStaffid})
    }    
    if (e.name) {
      that.setData({name: e.name})
    }     
    if (e.saleUid) {
      that.setData({saleUid: e.saleUid})
    }
    if (e.hasSaleUid == 1) {
      that.setData({saleUid: 0}); //hasSaleUid: 1没有卖券商家uid,2有卖券商家Uid
    }

    if (e.jump) {
      that.data.jump = e.jump;
    }  
    if (e.room_id) {//直播进入商品详情
      let custom_params = JSON.parse(decodeURIComponent(e.custom_params));
      let jump = 0;
      if (custom_params.saleUid && custom_params.saleUid > 0) {
        jump = 1;
      }
      that.data.jump = jump;
      that.setData({saleUid: custom_params.saleUid })
    }

    let isFriendState = app.globalData.isFriendState;
    if (e.seltoid) {//商家uid
      that.setData({seltoid: e.seltoid})
      if (isFriendState != 1 && app.globalData.userInfo) {
        that.getCart(e.seltoid);
      }
      if (!e.saleUid) {//没有推荐人
        getUserCard(e.seltoid, function (cardid) {
          wx.setStorageSync('cardId', cardid);
          that.data.procardid = cardid
        })
      }
    }
    if (isFriendState != 1) {
      that.getInfo();
    }
    that.getProductInfo(that.data.CurrentPid);
    that.getGoodsSku(that.data.CurrentPid);
  },

  toCart: function () {
    let that = this;
    let name = this.data.company;
    if (app.globalData.diningSid != 0) {
      wx.navigateTo({
        url: '/order/order/SessionCart/index?seltoid=' + that.data.seltoid,
      })
    } else {
      wx.navigateTo({
        url: '/order/order/cart/index?bossname=' + name + '&seltoid=' + that.data.seltoid,
      })
    }

  },

  addShopCar: function () {
    var that = this;
    let sumPrice = that.data.sumPrice;
    let cartNumber = that.data.cartNumber;
    // let productPrice = that.data.productPrice;
    let lastPrice = that.data.lastPrice;
    let buynumber = that.data.buynumber;
    let state = that.data.state;
    if (state == 1) {
      util.showModal('商品已下架'); return;
    }
    if (that.data.stockNumber <= buynumber) {
      util.showModal('商品库存不足'); return;
    }
    
    let path =  app.globalData.diningSid != 0 ?  '/api/cart/AddSessionProduct' : '/api/cart/AddProduct';
    let param = {
      uid: app.globalData.userInfo.Uid,
      pid: that.data.CurrentPid,
      buyCount: 1,
      optionIds: that.data.buyOptionIds,
      sid: app.globalData.diningSid,  //扫码点餐ID
      createUid: that.data.seltoid,
      saleUid: that.data.saleUid,      
    }  
    wx.request({
      url: app.globalData.host + path,
      data: param,
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          cartNumber = parseInt(cartNumber) + 1;
          sumPrice = parseFloat(sumPrice) + parseFloat(lastPrice);
          buynumber = parseInt(buynumber) + 1;
          that.setData({
            cartNumber: cartNumber,
            sumPrice: parseFloat(sumPrice).toFixed(2),
            buynumber: buynumber
          })
        } else {
          util.showModal('res.data.Message');         
        }
      }
    })
  },

  jianShopCar: function (e) {
    var that = this;
    let sumPrice = that.data.sumPrice;
    let cartNumber = that.data.cartNumber;
    let productPrice = that.data.productPrice;
    let buynumber = that.data.buynumber;
    let sellist = '0_' + that.data.CurrentPid;
    let upcount = parseInt(buynumber) - 1;
    sumPrice = parseFloat(sumPrice - productPrice).toFixed(2);
    cartNumber = parseInt(cartNumber - 1);

    let changeProductCount = 'ChangeProductCount';
    let param = {
      uid: app.globalData.userInfo.Uid,
      pid: that.data.CurrentPid,
      buyCount: upcount,
      selList: sellist,
      createUid: that.data.seltoid
    }

    if (app.globalData.diningSid != 0) {//扫码点餐
      changeProductCount = 'ChangeSessionProductCount';
      param = {
        pid: that.data.CurrentPid,
        buyCount: upcount,
        sid: app.globalData.diningSid,
        selList: sellist,
        optionIds: that.data.buyOptionIds
      }
    }
    wx.request({
      url: app.globalData.host + '/api/cart/' + changeProductCount,
      data: param,
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            cartNumber: cartNumber,
            sumPrice: sumPrice,
            buynumber: upcount
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  getCart: function (createUid) {
    let that = this;
    let path  = app.globalData.diningSid != 0 ?  '/api/Cart/SessionIndex' : '/api/Cart/Index';
    wx.request({
      url: app.globalData.host + path,
      data: {
        createUid: createUid,
        uid: app.globalData.userInfo.Uid, 
        sid: app.globalData.diningSid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.StoreCartList.length > 0) {
            let buynumber = 0;
            let cartResult = res.data.Data.StoreCartList[0].CartProductList;
            for (let i = 0; i < cartResult.length; i++) {
              if (cartResult[i].OrderProductInfo.Pid == that.data.CurrentPid) {
                buynumber = cartResult[i].OrderProductInfo.BuyCount;
              }
            }
            that.data.cartResult = cartResult;
            that.setData({
              cartNumber: res.data.Data.TotalCount,
              sumPrice: res.data.Data.OrderAmount,
              buynumber: buynumber
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  //是否授权登陆
  isLogin: function (back) {
    let that = this;
    let isAccredit = that.data.isAccredit;
    if (!isAccredit) {
      wx.showModal({
        title: '提示',
        content: '登陆小程序之后方可购买商品，是否确认登陆？',
        success: function (res) {
          if (res.confirm) {
            if (that.data.jump == 1) {
              wx.redirectTo({
                url: '../accredit/index?back=' + back + '&pid=' + that.data.CurrentPid + '&seltoid=' + that.data.seltoid + '&jump=1&saleUid=' + that.data.saleUid + '&name=' + that.data.name,
              })
            } else {
              wx.redirectTo({
                url: '../accredit/index?back=' + back,
              })
            }
          }
        }
      })
      return false;
    }
    return true;
  },

  onShow: function (e) {
    var that = this;
    that.data.startDate = util.formatTime(new Date());
  },

  /**
   * 会员的操作记录actionType = 22 查看商品详情
   */
  aiCardActionRecord: function (actionValue, staffId) {
    let cardId = wx.getStorageSync("cardId");
    if (staffId > 0) {
      cardId = staffId;
    }
    if (!app.globalData.userInfo) {
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/AddAiCardAction?staffId=' + cardId + '&uid=' + app.globalData.userInfo.Uid + '&actionType=22' + '&actionValue=' + encodeURIComponent(actionValue) + '&storeId=' + app.globalData.storeId + "&storeAppId=" + app.globalData.storeAppId,
      success: function (res) {
        if (res.data.Code == 0) {
          console.log("操作记录：" + actionValue)
        }
      },
    })
  },

  // 商品信息
  getProductInfo: function (pid = 0) {
    var that = this;
    wx.showLoading({title: '加载中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/Store/Product?pid=' + pid + '&isExtend=1&isLive=1&saleUid=' + that.data.saleUid,
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          var p = res.data.Data;
          let product = res.data.Data.ProductInfo;
          let expireTime = '';
          let jump = 0;
          let isUseNow = '';//是否购买后立即生效
          let limit = '';//是否限购
          let date = new Date(Date.parse(res.data.ServerTime.replace(/-/g, "/")));
          let outsaletime = '';
          let tobuyBtn = p.StockNumber == 0 ? '已售罄' : that.data.tobuyBtn;

          if (p.Extend) {     
            outsaletime = p.Extend.SendEndTime ?  p.Extend.SendEndTime : p.Extend.ExpireTime;
            expireTime = outsaletime.substr(0, 10);
            expireTime = expireTime.indexOf('1970') != -1 ? '永久有效' : expireTime;
            if (p.Extend.SendEndTime) {
              var date2 = new Date(Date.parse(p.Extend.SendEndTime.replace(/-/g, "/")));
              tobuyBtn = date2 < date ? '已售罄' : tobuyBtn;
            }

            if (p.Extend.AddUid > 0) {
              getUserCard(p.Extend.AddUid, function (cardid) {
                that.data.procardid = cardid;
              })
              that.getProductActoin(pid, p.Extend.AddUid);
              that.getBuyers(pid);
            }           
            //是否能赠送
            that.isSend(p.Extend, product.CateId);

            if (p.Extend.BrokeragePrice > 0) {        
              jump = 1; //9.9代金券
              if(product.CateId==377 || product.CateId==378){
                jump = 11;  //云加盟
              }
              var date3 = new Date(Date.parse(p.Extend.UseStartTime.replace(/-/g, "/")));
              if (date3 < date) {
                isUseNow = '付款后立即生效';
              }          
            }
          }


          let lastLiveList = [];
          let liveList = res.data.Data.LiveList ? res.data.Data.LiveList : [];
          for (let i = 0; i < liveList.length; i++) {
            liveList[i].CoverImg = util.formatAvater(liveList[i].CoverImg, 'https://static.711688.net.cn/upload/adv/');
            liveList[i].ShareImg = util.formatAvater(liveList[i].ShareImg, 'https://static.711688.net.cn/upload/adv/');
            liveList[i].status = '已过期';
            switch(liveList[i].LiveStatus){
              case 101: liveList[i].status = '直播中'; break;
              case 102: liveList[i].status = '未开始'; break;
              case 103: liveList[i].status = '已结束'; break;
              case 104: liveList[i].status = '禁播'; break;
              case 105: liveList[i].status = '暂停中'; break;
              case 106: liveList[i].status = '异常'; break;
            }
            if(liveList[i].status != '已过期'){
              lastLiveList.push(liveList[i]);
            } 
          }
          //头图
          let picPath= 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/';
          let imgList = p.ProductImageList ? p.ProductImageList: [];
          for (let i = 0; i < imgList.length; i++) {
            imgList[i].ShowImg = 
                imgList[i].ShowImg.indexOf('ps') != -1 ?
                util.formatAvaterByProHead(imgList[i].ShowImg) : 
                util.formatAvater(imgList[i].ShowImg, picPath);         
          }         
          //详情图
          let detailPics = product.DetailPics ? JSON.parse(product.DetailPics) : [];
          for (let i = 0; i < detailPics.length; i++) {
            detailPics[i] = util.formatAvater(detailPics[i], picPath);
          }

          if (res.data.Data.SinglePromotionInfo) {
            if (res.data.Data.SinglePromotionInfo.DayBuyCount > 0) {
              limit = '每天限购一份'; 
            } else {
              limit = '每天限购' + res.data.Data.SinglePromotionInfo.AllowBuyCount + '份';
            }
          }
          
          let isBackEditor = false;
          product.Description = product.Description.replace(/\r\n/g, '<br>');
          if (product.Description.indexOf('style=') != -1 || product.Description.indexOf('</p>') != -1) {
            isBackEditor = true;
          }         

          that.setData({
            cateId: product.CateId,
            productName: product.Name,
            productPrice: product.ShopPrice,
            lastPrice: product.ShopPrice,
            vid: product.VID,
            description: product.Description,
            pimages: p.ProductImageList[0].ShowImg,
            DetailPics: detailPics,
            ShadowPrice: product.ShadowPrice,
            marketPrice: product.MarketPrice,
            productImageList: imgList,
            stockNumber: p.StockNumber,
            ExpireTime: expireTime,
            state: product.State,
            lastLiveList: lastLiveList,
            salecount: product.SaleCount,
            tobuyBtn: tobuyBtn,
            isBackEditor: isBackEditor,
            isUseNow: isUseNow,//是否购买后立即生效
            limit: limit,//是否限购
            serverTime: res.data.ServerTime,
            outsaletime: outsaletime,
            jump: jump,
            regions: p.Extend ? p.Extend.Regions.split(',') : ''
          })
     
          WxParse.wxParse('article', 'html', product.Description, that, 5);
          let isFriendState = app.globalData.isFriendState;
          if (isFriendState != 1) {
            that.aiCardActionRecord(product.Name, that.data.proStaffid);
          }
          that.getImgInfoHeight(imgList);
        } else {
          util.showModal(res.data.Message);       
        }
      },
    })
  },

  getGoodsSku: function (pid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/product/GetProductOptionListByPid?pid=' + pid,
      success: function (res) {
        if (res.data.Code == 0) {
          let buyOptionIds = '';
          let selectSkuname = '';
          let list = res.data.Data;
          let optionPrice = 0;
          for (let i = 0; i < list.length; i++) {
            list[i].selOptionid = list[i].OptionList[0].OptionId;
            list[i].selOptionName = list[i].OptionList[0].Name;
            list[i].selOptionPrice = list[i].OptionList[0].Price;
            selectSkuname += list[i].selOptionName + "、";
            buyOptionIds += list[i].selOptionid + ',';//选择要购买的产品规格
            list[i].OptionList[0].isSelect = true;
            optionPrice += list[i].selOptionPrice;
          }
          selectSkuname = selectSkuname.substr(0, selectSkuname.length - 1);
          buyOptionIds = buyOptionIds.substr(0, buyOptionIds.length - 1);
          that.setData({
            skulist: list,
            selectSkuname: selectSkuname,
            optionPrice: optionPrice,
            buyOptionIds: buyOptionIds
          })
        } else {
          util.showModal(res.data.Message);         
        }
      }
    })
  },

  //是否支持赠送
  isSend :function(extend, cateId){
    var that = this;
    if(cateId==377 || cateId==378){
      return;
    }
    if(extend || extend.CouponTypeId == 0){
      wx.request({
        url: app.globalData.host + '/api/product/GetCardProduct',
        success: function (ress) {
          if (ress.data.Code == 0) {
            let jjkList = ress.data.Data;
            if (extend.Pid != jjkList[0].Pid) {
              that.setData({isSend: '支持转赠'});  //非玖玖卡，可以转赠
            }
          }
        }
      })
    }    
  },

  selectSku: function (e) {
    let that = this;
    let ismultiple = e.currentTarget.dataset.ismultiple;//是单选或多选规格
    let optionid = e.currentTarget.dataset.optionid;
    let name = e.currentTarget.dataset.name;
    let tagid = e.currentTarget.dataset.tagid;
    let proSkulist = that.data.skulist;
    let optionPrice = e.currentTarget.dataset.price;
    let selectSkuname = '';
    let buyOptionIds = '';
    let selectPrice = 0;
    for (let i = 0; i < proSkulist.length; i++) {
      if (!Array.isArray(proSkulist[i].selOptionid) && !Array.isArray(proSkulist[i].selOptionName)) {
        proSkulist[i].selOptionid = proSkulist[i].selOptionid.toString().split();
        proSkulist[i].selOptionName = proSkulist[i].selOptionName.split('、');
      }
      if (!Array.isArray(proSkulist[i].selOptionPrice)) {
        proSkulist[i].selOptionPrice = proSkulist[i].selOptionPrice.toString().split();
      }
      if (tagid == proSkulist[i].TagId) {
        if (proSkulist[i].selOptionid.indexOf(optionid.toString()) == -1) {//之前未选中
          if (ismultiple == 0) {//单选规格
            proSkulist[i].selOptionid = [];
            proSkulist[i].selOptionName = [];
            proSkulist[i].selOptionPrice = [];
          }
          proSkulist[i].selOptionid.push(optionid.toString());
          proSkulist[i].selOptionName.push(name);
          proSkulist[i].selOptionPrice.push(optionPrice.toString());
          for (let j = 0; j < proSkulist[i].OptionList.length; j++) {
            if (ismultiple == 1) {
              if (proSkulist[i].OptionList[j].OptionId == optionid) {
                proSkulist[i].OptionList[j].isSelect = true;
              }
            } else {//单选
              if (proSkulist[i].OptionList[j].OptionId == optionid) {
                proSkulist[i].OptionList[j].isSelect = true;
              } else {
                proSkulist[i].OptionList[j].isSelect = false;
              }
            }
          }
        } else {//已有则取消
          let index = proSkulist[i].selOptionid.indexOf(optionid.toString());//钙元素在数组中的下标
          let index2 = proSkulist[i].selOptionName.indexOf(name);//钙元素在数组中的下标
          let index3 = proSkulist[i].selOptionPrice.indexOf(optionPrice.toString());//该元素在数组中的下标
          proSkulist[i].selOptionid.splice(index, 1);
          proSkulist[i].selOptionName.splice(index2, 1);
          proSkulist[i].selOptionPrice.splice(index3, 1);
          for (let j = 0; j < proSkulist[i].OptionList.length; j++) {
            if (proSkulist[i].OptionList[j].OptionId == optionid) {
              proSkulist[i].OptionList[j].isSelect = false;
            }
          }
        }
      }
      selectSkuname += proSkulist[i].selOptionName.join('、') + '、';
      buyOptionIds += proSkulist[i].selOptionid.join(',') + ',';
      let priceList = proSkulist[i].selOptionPrice;
      for(let k =0; k < priceList.length; k++){
        selectPrice += parseFloat(priceList[k]);
      }
    }
    let startIndex = 0;
    let startIndex2 = 0;
    if (selectSkuname.indexOf('、') == 0) {
      startIndex = 1;
    }
    if (buyOptionIds.indexOf(',') == 0) {
      startIndex2 = 1;
    }
    selectSkuname = selectSkuname.substr(startIndex2, selectSkuname.length - (startIndex2 + 1));
    buyOptionIds = buyOptionIds.substr(startIndex, buyOptionIds.length - (startIndex + 1));
    let lastPrice = parseFloat(that.data.productPrice) + selectPrice;
    that.data.buyOptionIds = buyOptionIds;
    that.setData({
      skulist: proSkulist,
      selectSkuname: selectSkuname,
      lastPrice: parseFloat(lastPrice).toFixed(2)
    })
  },

  closeSkudialog: function () {
    this.setData({
      showDialog: !this.data.showDialog
    })
  },

  addShopCarSku: function () {
    var that = this;
    // let price = that.data.productPrice;
    let lastPrice = that.data.lastPrice;
    let cartNumber = that.data.cartNumber;
    let cartSumPrice = that.data.sumPrice;
    let buynumber = that.data.buynumber;
    if (that.data.state == 1) {
      util.showToast('商品已下架'); return;
    }
    let back = '/pages/classes-new/index';
    if(!that.isLogin(back)){
      return;
    }
 
    let path =  app.globalData.diningSid != 0 ?  '/api/cart/AddSessionProduct' : '/api/cart/AddProduct';
    let param = {
      uid: app.globalData.userInfo.Uid,
      pid: that.data.CurrentPid,
      buyCount: 1,
      optionIds: that.data.buyOptionIds,
      sid: app.globalData.diningSid,  //扫码点餐ID
      createUid: that.data.seltoid,
      saleUid: that.data.saleUid,      
    }  
    wx.request({
      url: app.globalData.host + path,
      data: param,
      success: function (res) {
        if (res.data.Code == 0) {
          cartNumber += 1;
          cartSumPrice = parseFloat(cartSumPrice) + parseFloat(lastPrice);
          that.setData({
            cartNumber: cartNumber,
            sumPrice: parseFloat(cartSumPrice).toFixed(2),
            buynumber: buynumber + 1
          });
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000
          })
        } else {
          util.showModal(res.data.Message);        
        }
      }
    })
  },
  jianShopCarSku: function () {
    var that = this;
    var pid = that.data.CurrentPid;
    let price = that.data.productPrice;
    let cartNumber = that.data.cartNumber;
    let cartSumPrice = that.data.cartSumPrice;
    let buynumber = that.data.buynumber;
    let sellist = '0_' + pid;
    let upcount = buynumber - 1;
    cartSumPrice -= price;
    cartNumber -= 1;

    let changeProductCount = 'ChangeProductCount';
    let param = {
      uid: app.globalData.userInfo.Uid,
      pid: pid,
      buyCount: upcount,
      selList: sellist,
      createUid: that.data.seltoid
    }

    if (app.globalData.diningSid != 0) {//扫码点餐
      changeProductCount = 'ChangeSessionProductCount';
      param = {
        pid: pid,
        buyCount: upcount,
        sid: app.globalData.diningSid,
        selList: sellist,
        optionIds: that.data.buyOptionIds
      }
    }

    wx.request({
      url: app.globalData.host + '/api/cart/' + changeProductCount,
      data: param,
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            cartNumber: cartNumber,
            cartSumPrice: parseFloat(cartSumPrice).toFixed(2),
            buynumber: upcount
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //设置图片自适应
  getImgInfoHeight: function (list) {
    var that = this;
    var heightArr = [];
    var f = 0;
    for (let h = 0; h < list.length; h++) {
      wx.getImageInfo({
        src: list[h].ShowImg,
        success: function (res) {
          list[h].width = res.width;
          list[h].height = res.height;
        },

        complete: function (res) {
          f++
          if (f == list.length) {
            console.log('执行完毕');
            for (let g = 0; g < list.length; g++) {
              //获取图片真实宽度  
              var imgwidth = list[g].width,
                imgheight = list[g].height,
                //宽高比  
                ratio = imgwidth / imgheight;
              //计算的高度值  
              var viewHeight = 750 / ratio;
              var vieheight = viewHeight
              heightArr.push(vieheight)
              list[g].imgheight = vieheight;
            }
            for (let t = 0; t < list.length; t++) {
              var maxN = that.checkMax(heightArr)
              list[t].maxHeight = maxN;
            }
            that.setData({
              productImageList: list
            })
          }
        }
      })
    }
  },

  getInfo: function () {
    let that = this;
    let cardid = wx.getStorageSync("cardId");
    if (cardid) {
      wx.request({
        url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardid,
        success: function (res) {
          if (res.data.Code == 0) {            
            that.data.createUid = res.data.Data.Uid;
            that.data.company = res.data.Data.Company;
            that.data.mobile = res.data.Data.Mobile;            
          }
        }
      })
    }
  },

  //判断最大值
  checkMax: function (heightArr) {
    var maxN = Math.max.apply(null, heightArr);
    return maxN;
  },

  //事件处理函数
  swiperchange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },

  // 联系商家
  makeCallPhone: function () { 
    let that = this;    
    if(that.data.proStaffid>0){
      wx.request({
        url: app.globalData.host + '/api/Staff/GetStaff?id=' + that.data.proStaffid,
        success: function (res) {
          if (res.data.Code == 0) {   
            that.data.mobile = res.data.Data.Mobile;        
            wx.makePhoneCall({
              phoneNumber: that.data.mobile
            })                    
          }
        }
      })
    }else if(that.data.mobile){   
        wx.makePhoneCall({
          phoneNumber: that.data.mobile
        })
    }    
  },

  //轮播图预览
  preViewImg: function (e) {
    let list = this.data.productImageList;
    let src = e.currentTarget.dataset.src;
    let imgs = [];
    for (let i = 0; i < list.length; i++) {
      imgs.push(list[i].ShowImg)
    }
    imgs.join(",");
    wx.previewImage({
      current: src,
      urls: imgs,
    })
  },
  //商品详情图片预览
  preViewDetailsImg: function (e) {
    let list = this.data.DetailPics;
    let src = e.currentTarget.dataset.src;
    let imgs = [];
    for (let i = 0; i < list.length; i++) {
      imgs.push(list[i])
    }
    imgs.join(",");
    wx.previewImage({
      current: src,
      urls: imgs,
    })
  },

  //调用子组件的方法
  getSharePoster: function () {
    this.setData({
      showVideo: false
    })
    this.selectComponent('#getPoster').getAvaterInfo()
  },

  myEventListener: function (e) {
    this.setData({
      showVideo: true
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    util.recordActionTime(this.data.startDate, 22, this.data.CurrentPid)
  },

  onUnload: function () {
    util.recordActionTime(this.data.startDate, 22, this.data.CurrentPid)
  },

  onShareAppMessage: function (res) {
    var that = this;
    var cardid = wx.getStorageSync("cardId");
    var path ='/pages/index/index?id=' + cardid + '&source=2' + '&pid=' + that.data.CurrentPid + '&saleUid=' + that.data.saleUid + '&seltoid=' + that.data.seltoid + '&proStaffid=' + that.data.proStaffid;
    console.log(path);
    return {
      imageUrl: that.data.productImageList[0].ShowImg,
      title: that.data.productName,
      path: path,
      success: function (res) {
        util.showModal('转发成功');       
      }
    }
  },
  onShareTimeline: function (e) {
    let that = this;
    let path = 'pid=' + that.data.CurrentPid + '&seltoid=' + that.data.seltoid + '&saleUid=' + that.data.saleUid + '&isFriendState=1&id=' + that.data.procardid + '&proStaffid=' + that.data.proStaffid;
    console.log(path)
    return {
      title: that.data.productName,
      query: path,
      imageUrl: that.data.pimages
    }
  },
  //监听用户滑动页面事件
  onPageScroll: function (e) {
    let top = parseInt(e.scrollTop) + 60;
    this.setData({
      top: top
    })
  }
})